const initialState = {
  arr:[], // 渲染列表数组
  shoparr: JSON.parse(window.localStorage.getItem("shopcar"))  || [] ,// 购物车数组，
  flagall: (window.localStorage.getItem("flagall")==="true"?true :false) ||false , // 用于控制全选的
  floorarr:[],
  addressarr:[
    {
      name:"雷雷",
      address:"上海市长宁区",
      phone:13522402123
    }  
  ]
}

export default (state = initialState, { type, payload,payload1 }) => {
  let newState = JSON.parse(JSON.stringify(state))
  switch (type) {

  case "getlist":
    if (payload1) {
       newState.arr = [... newState.arr ,...payload]
    } else {
      newState.arr = payload
    }
    return newState
  case "addshop" :
   let findindex =  newState.shoparr.findIndex((item,index)=>{
      return item.id === payload.id
   })
  
   // findindex 寻找数组元素的下标，如果找到了，返回下标，如果找不到返回-1
   if (findindex !== -1) {
     alert("您已经加入过购物车了")
   } else {
     newState.shoparr.push(payload)
   }
    window.localStorage.setItem("shopcar",JSON.stringify( newState.shoparr))
   return newState
   case "addFn" :
     newState.shoparr.forEach(item=>{
       if (item.id === payload) {
         item.num ++ 
       }
     })
     window.localStorage.setItem("shopcar",JSON.stringify( newState.shoparr))
     return newState
  case "delFn" :
    newState.shoparr.forEach(item=>{
      if (item.id === payload) {
        item.num -- 
        if (item.num < 1) {
          item.num =1
        }
      }
    })
    window.localStorage.setItem("shopcar",JSON.stringify( newState.shoparr))
    return newState
   case "changeitem" :
    newState.shoparr.forEach(item=>{
      if (item.id === payload) {
        item.checked = !item.checked
      }
    })
   let grades =  newState.shoparr.every(item=>{
      return item.checked
    })
    newState.flagall = grades
    window.localStorage.setItem("flagall", newState.flagall.toString())
    window.localStorage.setItem("shopcar",JSON.stringify( newState.shoparr))
    return newState
    case "changeAll":
      newState.flagall = !newState.flagall
      newState.shoparr.forEach(item=>{
        item.checked =  newState.flagall
      })
      window.localStorage.setItem("flagall", newState.flagall.toString())
      window.localStorage.setItem("shopcar",JSON.stringify( newState.shoparr))
      return newState
    case "getfloorlist" :
      newState.floorarr = payload
      return newState
    case "addaddress" :
      newState.addressarr.push(payload)
      return newState
    case "delfn":
      newState.addressarr.splice(payload,1)
      return  newState
    case "editfn":
      newState.addressarr.splice(payload.index,1,payload)
      return  newState
  default:
    return state
  }
}
